/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.anniversary.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.annotation.rest.AnonymousPostMapping;
import me.zhengjie.modules.anniversary.domain.Department;
import me.zhengjie.modules.anniversary.domain.Teacher;
import me.zhengjie.modules.anniversary.repository.DepartmentRepository;
import me.zhengjie.modules.anniversary.service.DepartmentService;
import me.zhengjie.modules.anniversary.service.TeacherService;
import me.zhengjie.modules.anniversary.service.dto.TeacherDto;
import me.zhengjie.modules.anniversary.service.dto.TeacherQueryCriteria;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
* @website https://el-admin.vip
* @author Jiayin Wei
* @date 2020-07-28
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "教职工校友管理")
@RequestMapping("/api/teacher")
public class TeacherController {
    private final PasswordEncoder passwordEncoder;
    private final TeacherService teacherService;
    private final UserService userService;

    private final UserMapper userMapper;
    private final DeptService deptService;
    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('teacher:list')")
    public void download(HttpServletResponse response, TeacherQueryCriteria criteria) throws IOException {
        teacherService.download(teacherService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询教职工校友")
    @ApiOperation("查询教职工校友")
    @PreAuthorize("@el.check('teacher:list')")
    public ResponseEntity<Object> query(TeacherQueryCriteria criteria, Pageable pageable){
        return new ResponseEntity<>(teacherService.queryAll(criteria,pageable),HttpStatus.OK);
    }

    @PostMapping
    @Log("新增教职工校友")
    @ApiOperation("新增教职工校友")
    @PreAuthorize("@el.check('teacher:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody Teacher resources){
        return new ResponseEntity<>(teacherService.create(resources),HttpStatus.CREATED);
    }
    @PostMapping(value = "/batchImport")
    @Log("批量导入教职工校友")
    @ApiOperation("批量导入教职工校友")
    @PreAuthorize("@el.check('teacher:add')")
    public  ResponseEntity<Object> batchImport(MultipartFile file, HttpServletResponse response) throws IOException {
        return new ResponseEntity<>(teacherService.batchImport(file,response), HttpStatus.OK);
    }
    @PutMapping
    @Log("修改教职工校友")
    @ApiOperation("修改教职工校友")
    @PreAuthorize("@el.check('teacher:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody Teacher resources){
        Boolean isVerifyChange = false;
        //若原认证状态不是 0 且认证状态有更改，则需要更新认证时间
        TeacherDto teacher = teacherService.findById(resources.getId());
        if(teacher != null && teacher.getVerifyStatus() != 0 && teacher.getVerifyStatus() != resources.getVerifyStatus()){
            isVerifyChange = true;
            resources.setVerifyTime(new Timestamp(System.currentTimeMillis()));
        }

        teacherService.update(resources);
        //同步用户与教师信息表的认证状态
        if(resources.getTeacherUser() != null){
            User user =  userMapper.toEntity(userService.findById(resources.getTeacherUser().getId()));
            user.setVerifyStatus(resources.getVerifyStatus());
            if(isVerifyChange)
                user.setVerifyTime(resources.getVerifyTime());
            userService.update(user);
        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除教职工校友")
    @ApiOperation("删除教职工校友")
    @PreAuthorize("@el.check('teacher:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Long[] ids) {
        teacherService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Log("通过姓名和电话查询教师")
    @ApiOperation("通过姓名和电话查询教师")
    @AnonymousPostMapping(value = "/selteacher")
    public ResponseEntity<Object> selteacher(@RequestBody User user) {
        System.out.println(user.toString());
        Teacher teacher = teacherService.findByNameAndPhone(user.getUsername(), user.getPhone());

        if (teacher != null){
            user.setVerifyStatus(1);
            user.setEmail(teacher.getPhone() + "@139.com");
            user.setDept(teacher.getDepartment());
            user.setDeptId(teacher.getDepartment().getId());
        }else{
            user.setVerifyStatus(0);
            user.setEmail("139@139.com");
        }
        //判断是否存在
        user.setCreateBy("微信认证");
        System.out.println("selteacher:" + user.getWxOpenId());
        user.setPassword(passwordEncoder.encode("123456"));
        user.setIsAdmin(false);
        user.setEnabled(true);
        user.setWxNickName("2");
        UserDto userDto = userService.create(user);
        if(teacher != null){
            teacher.setUserId(userDto.getId());
            teacher.setVerifyStatus(1);
            teacherService.update(teacher);
        }
        return ResponseEntity.ok(user);
    }
}
